package cn.edu.cqut.mdm.core.dispatcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.sf.json.JSONObject;
import cn.edu.cqut.mdm.core.message.RequestMessage;
import cn.edu.cqut.mdm.core.message.ResponseMessage;

public class JsonDispatcher implements Dispatcher {
	private static final String CALL_PATH = "json.do";
	private static JsonDispatcher jsonDispatcher = new JsonDispatcher();

	private JsonDispatcher() {
	}

	public static JsonDispatcher getJsonDispatcher() {
		return jsonDispatcher;
	}

	@Override
	public ResponseMessage dispatch(RequestMessage requestMessage) {
		String serverUrl = requestMessage.getUrl();
		if (serverUrl == null) {
			return null;
		}
		URL url;
		if (!serverUrl.startsWith("http://")) {
			serverUrl = "http://" + serverUrl;
		}
		if (!serverUrl.endsWith("/")) {
			serverUrl = serverUrl + "/";
		}
		serverUrl = serverUrl + CALL_PATH;
		try {
			url = new URL(serverUrl);
			HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();
			httpurlconnection.setRequestMethod("POST");
			httpurlconnection.setDoOutput(true);
			String json = JSONObject.fromObject(requestMessage).toString();
			httpurlconnection.getOutputStream().write(("json=" + json).getBytes());
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((InputStream) httpurlconnection.getContent()));
			json = bufferedReader.readLine();
			json = new String(json.getBytes(), "utf-8");
			ResponseMessage responseMessage = (ResponseMessage) JSONObject.toBean(JSONObject.fromObject(json), ResponseMessage.class);
			return responseMessage;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
